﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reactive.Linq;
using System.Reactive.Concurrency;
using System.Text.RegularExpressions;

namespace IntroApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            var c = new SampleClient();
        }

        private void Form1_Load(object sender2, EventArgs evt)
        {
            Observable.FromEvent<EventHandler, EventArgs>(
                h => (sender, e) => h(e),
                h => this.textBox1.TextChanged += h,
                h => this.textBox1.TextChanged -= h)
                .Throttle(TimeSpan.FromSeconds(1))
                .Select(_ => this.textBox1.Text)
                .Where(s => Regex.IsMatch(s, "^[0-9]+$"))
                .ObserveOn(this)
                .Do(_ => this.textBox1.Enabled = false)
                .SelectMany(s => 
                {
                    var client = new SampleClient();
                    return Observable.FromAsyncPattern<int, int>(
                        client.BeginCalc,
                        client.EndCalc).Invoke(int.Parse(s));
                })
                .ObserveOn(this)
                .Subscribe(
                    s =>
                    {
                        MessageBox.Show("OK : " + s);
                        this.textBox1.Enabled = true;
                    },
                    ex =>
                    {
                        MessageBox.Show("Error : " + ex.Message);
                        this.textBox1.Enabled = true;
                    },
                    () =>
                    {
                        MessageBox.Show("Completed");
                    });

        }
    }
}
